# !/usr/bin/env python
# -*- coding: utf-8 -*-


import threading, time

# 当多个线程几乎同时修改某一个共享数据的时候，需要进行同步控制。线程同步能够保证多个线程安全访问竞争资源，最简单的同步机制是引入互斥锁

# 定义一个全局变量
g_num = 0


def work1():
    # 申明g_num是一个全局变量
    global g_num

    lock.acquire()  # 加锁
    for i in range(1000000):
        g_num += 1
    lock.release()  # 解锁
    print("work1------%d\n" % g_num)


def work2():
    global g_num

    lock.acquire()
    for i in range(1000000):
        g_num += 1
    lock.release()
    print("work2------%d\n" % g_num)


if __name__ == '__main__':
    # 创建一把互斥锁
    lock = threading.Lock()

    t1 = threading.Thread(target=work1)
    t2 = threading.Thread(target=work2)

    t1.start()
    t2.start()

    # 在子线程结束后打印g_num
    while len(threading.enumerate()) != 1:
        time.sleep(1)
    print("main------", g_num)